package org.example.config;

import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.data.redis")
	public RedisProperties redisProperties() {
		return new RedisProperties();
	}

	@Bean
	public RedisConnectionFactory redisConnectionFactory(RedisProperties redisProperties) {
		// Cluster mode
		RedisProperties.Cluster cluster = redisProperties.getCluster();
		if (cluster != null && cluster.getNodes() != null && !cluster.getNodes().isEmpty()) {
			RedisClusterConfiguration cfg = new RedisClusterConfiguration(cluster.getNodes());
			if (redisProperties.getPassword() != null) {
				cfg.setPassword(RedisPassword.of(redisProperties.getPassword()));
			}
			return new LettuceConnectionFactory(cfg);
		}

		// Sentinel mode
		RedisProperties.Sentinel sentinel = redisProperties.getSentinel();
		if (sentinel != null && sentinel.getNodes() != null && !sentinel.getNodes().isEmpty()) {
			RedisSentinelConfiguration cfg = new RedisSentinelConfiguration();
			cfg.master(sentinel.getMaster());
			sentinel.getNodes().forEach(node -> {
				String[] parts = node.split(":");
				cfg.sentinel(parts[0], Integer.parseInt(parts[1]));
			});
			if (redisProperties.getPassword() != null) {
				cfg.setPassword(RedisPassword.of(redisProperties.getPassword()));
			}
			return new LettuceConnectionFactory(cfg);
		}

		// Standalone mode (default)
		RedisStandaloneConfiguration cfg = new RedisStandaloneConfiguration();
		cfg.setHostName(redisProperties.getHost());
		cfg.setPort(redisProperties.getPort());
		cfg.setDatabase(redisProperties.getDatabase());
		if (redisProperties.getPassword() != null) {
			cfg.setPassword(RedisPassword.of(redisProperties.getPassword()));
		}
		return new LettuceConnectionFactory(cfg);
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		return new StringRedisTemplate(redisConnectionFactory);
	}
}
